package com.asamioffice.goldenport.util

import scala.collection.immutable
import scala.collection.mutable.ArrayBuffer
import scala.util.matching.Regex

/**
 * @since   Sep. 21, 2010
 * @version Oct.  4, 2010
 * @version Dec.  4, 2011
 * @author  ASAMI, Tomoharu
 */
class RegexRegistry[T]() {
  private var _registry = new ArrayBuffer[(Regex, T)]

  def +=(kv: Tuple2[Regex, T]): RegexRegistry[T] = {
    _registry += kv
    _registry = _registry.sortWith((lhs, rhs) => lhs._1.toString.length > rhs._1.toString.length)
    this
  }

  def find(key: String): Option[T] = {
    require (key != null)
    _registry.find(_._1.findPrefixMatchOf(key).isDefined).map(_._2)
  }

  def find2(key: String): Option[(Regex, T)] = {
    require (key != null)
    _registry.find(_._1.findPrefixMatchOf(key).isDefined)
  }

  def exists(key: String): Boolean = {
    _registry.exists(_._1 == key)
  }

  def getOption(key: String): Option[T] = {
    _registry.find(_._1 == key).map(_._2)
  }

  def registry = _registry.toList
}
